<template>
  <div>
    <Title title="供应商信息" style="margin-bottom: 16px;" />
    <el-form
      ref="formRef"
      :model="paramsObj"
      :rules="formRules"
      :label-width="labelWidth"
      :label-position="showMobilePage ? 'left' : 'right'"
      class="lineHeight32">
      <el-row type="flex" class="response-el-row">
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item :class="{'dynamic-item-margin': !showMobilePage}" label="供应商名称" prop="channelName">
            <el-autocomplete
              v-model.trim="paramsObj.channelName"
              :fetch-suggestions="querySearch"
              :maxlength="50"
              :class="showSupplierTip ? 'without-supplier-id' : ''"
              class="width172"
              size="small"
              placeholder="输入供应商名称"
              @change="channelNameChange"
              @select="handleSelect"
            />
            <div class="expend-btn" @click.stop="toCreateSupplier">快速新建</div>
            <span v-if="showSupplierTip" class="supplier-tip">请选择供应商</span>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="创建人" prop="createUser" style="margin-bottom: 7px;">
            <el-input v-model="paramsObj.createUser" class="width240" disabled type="text" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="所属部门" prop="departmentId" style="margin-bottom: 7px;">
            <el-cascader
              v-model="paramsObj.departmentId"
              :show-all-levels="false"
              :options="deptTreeList"
              :props="{
                emitPath:false,
                value: 'id',
                label: 'name',
                checkStrictly: true,
                multiple: false,
              }"
              class="width240"
              placeholder="请选择所属部门"
              size="small"
              collapse-tags
              clearable
              filterable
            >
              <template slot-scope="{ data }">
                <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                  <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                  <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                </el-tooltip>
                <span v-else>{{ data.name }}</span>
              </template>
            </el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-loading="supplierQueryLoading" :class="{'dividing': !showMobilePage}" type="flex" class="response-el-row static-form-fields">
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="供应商类型:" prop="supplierType">
            <ToolTip :content="paramsObj.supplierType | supplierTypeFilter" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="供应商编号:" >
            <ToolTip :content="paramsObj.supplierId || paramsObj.channelSn || paramsObj.supplierCode" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="可抵扣税率:" prop="taxRate">
            <ToolTip :content="(paramsObj.taxRate || paramsObj.taxRate === 0) ? `${paramsObj.taxRate}%` : ''" />
          </el-form-item>
        </el-col>
        <el-col v-if="isCompany" :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="纳税人识别号:" prop="taxpayerIdentificationNumber">
            <ToolTip :content="paramsObj.taxpayerIdentificationNumber" />
          </el-form-item>
        </el-col>
        <el-col v-if="isPersonal" :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="性别:" prop="sex">
            <ToolTip :content="paramsObj.sex | sexFilter" />
          </el-form-item>
        </el-col>
        <el-col v-if="isPersonal" :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="手机号码:" prop="phone">
            <ToolTip :content="paramsObj.phone" />
          </el-form-item>
        </el-col>
        <el-col v-if="isPersonal" :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="身份证:" prop="idCard">
            <FileShowList :file-list="paramsObj.idCard" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="地域:" prop="region">
            <ToolTip :content="paramsObj.region ? paramsObj.region.replace(/,/g, '-') : ''" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="快递地址:" prop="address">
            <ToolTip :content="paramsObj.address" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="微信号:" prop="wxCode">
            <ToolTip :content="paramsObj.wxCode" />
          </el-form-item>
        </el-col>
        <el-col v-if="isPersonal" :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="刊例状态:" prop="publishedStatus">
            <ToolTip :content="paramsObj.publishedStatus | publishedStatusFilter" />
          </el-form-item>
        </el-col>
        <el-col v-if="isCompany" :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="合作状态:" prop="cooperationStatus">
            <ToolTip :content="paramsObj.cooperationStatus | cooperationStatusFilter" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="备注:" prop="remark">
            <ToolTip :content="paramsObj.remark" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
/**
 *签约审批和销售供应商共用
 */
// components
import Title from '@/components/Title';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import ThreeLevelArea from '@/components/ThreeLevelArea';
import upAttachment from '@/components/Common/upAttachment/index';
import TagSelect from '@/components/Common/tagSelect';
import FileShowList from '@/components/CreateOrder/fileShowList';
// api
import { supplierManageList } from '@/api/supplier';
import { getDepartmentAll } from '@/api/config';
import { supplierInfo } from '@/api/supplier';
// tool
import { mapState } from 'vuex';
import { percentRate } from '@/utils/numFormat';
import { TAG_MODULES } from '@/utils/const';
import { hasRouteAuth } from '@/utils/permission';
import { getFirstDepartment } from '@/utils/index';
export default {
  components: { Title, selectWithoutHttp, ThreeLevelArea, upAttachment, TagSelect, FileShowList },
  filters: {
    supplierTypeFilter(val) {
      return {
        0: '个人',
        1: '公司'
      }[val] || null;
    },
    sexFilter(val) {
      return {
        0: '男',
        1: '女'
      }[val] || null;
    },
    publishedStatusFilter(val) {
      return {
        0: '正常上刊',
        1: '解约下刊',
        2: '处罚停刊'
      }[val] || null;
    },
    cooperationStatusFilter(val) {
      return {
        0: '正常合作',
        1: '终止合作'
      }[val] || null;
    }
  },
  model: {
    prop: 'paramsObj',
    event: 'changeValue'
  },
  props: {
    paramsObj: {
      type: Object,
      default: () => {
        return {};
      }
    },
    labelWidth: {
      type: String,
      default: '100px'
    },
    moduleType: {
      type: Number,
      default: TAG_MODULES.SETTLE_SUPPLIER
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    rowSpan: {
      type: Number,
      default: 12
    },
    showMobilePage: {
      type: Boolean,
      default: false
    },
    isDraft: { // 未发起审批
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      TAG_MODULES,
      formRules: {
        channelName: [{ required: true, trigger: 'change', message: '请输入供应商名称' }],
        departmentId: [{ required: true, trigger: 'change', message: '请选择所属部门' }]
      },
      deptTreeList: [],
      supplierTypeOptions: [{ id: 0, label: '个人' }, { id: 1, label: '公司' }],
      articlesStatusOptions: [{ id: 0, label: '正常上刊' }, { id: 1, label: '解约下刊' }, { id: 2, label: '处罚停刊' }],
      cooperationStatusOptions: [{ id: 0, label: '正常合作' }, { id: 1, label: '终止合作' }],
      isInitId: false,
      supplierQueryLoading: false
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    showSupplierTip() {
      return this.paramsObj.channelName && !this.paramsObj.channelId;
    },
    baseEmptySupplierInfo() { // 供应商选中联动字段默认值
      return {
        supplierType: '',
        supplierCode: '',
        supplierId: '',
        channelSn: '',
        cooperationStatus: '',
        taxpayerIdentificationNumber: '',
        publishedStatus: '',
        sex: '',
        taxRate: '',
        region: '',
        address: '',
        phone: '',
        wxCode: '',
        idCard: [],
        remark: ''
      };
    },
    isPersonal() { // 供应商类型：个人
      return this.paramsObj.supplierType === 0;
    },
    isCompany() { // 供应商类型：公司
      return this.paramsObj.supplierType === 1;
    }
  },
  watch: {
    'paramsObj.channelId'(id) {
      if (this.isInitId) return;
      !id ? this.resetSupplierInfo() : this.supplierDetail(id);
    }
  },
  created() {
    this.queryDeptTreeList();
    this.paramsObj.createUser = this.userInfo.userName;
    const departmentAry = this.userInfo.departmentAry;
    this.paramsObj.departmentId = this.getFirstDepartment(departmentAry);
    this.$emit('changeValue', this.paramsObj);
  },
  methods: {
    hasRouteAuth,
    getFirstDepartment,
    // 供应商详情
    supplierDetail(id) {
      this.supplierQueryLoading = true;
      supplierInfo(id).then(res => {
        this.setSupplierDataInfo(res.data || {});
        this.supplierQueryLoading = false;
      }).catch(err => {
        this.supplierQueryLoading = false;
        console.error(err);
      });
    },
    setSupplierDataInfo(data) {
      Object.keys(this.baseEmptySupplierInfo).forEach(key => {
        this.paramsObj[key] = data[key];
      });
      this.$emit('setAccountsReceivable', data.accountsReceivable && data.accountsReceivable.list || []);
    },
    resetSupplierInfo() {
      Object.keys(this.baseEmptySupplierInfo).forEach(key => {
        this.paramsObj[key] = this.baseEmptySupplierInfo[key];
      });
      this.$emit('setAccountsReceivable', []);
    },
    setSupplierInfo(id) { // 编辑(草稿中的编辑除外)首次渲染不请求供应商详情赋值
      if (this.isDraft) {
        this.paramsObj.channelId = id;
      } else {
        this.isInitId = true;
        this.paramsObj.channelId = id;
        this.$nextTick(() => {
          this.isInitId = false;
        });
      }
    },
    deductionRateInput(value) {
      const str = percentRate(value);
      this.paramsObj.taxRate = str;
      this.$emit('changeValue', this.paramsObj);
    },
    setWxCode(val) {
      this.paramsObj.wxCode = val.replace(/[\u4e00-\u9fa5]/g, '');
      this.$emit('changeValue', this.paramsObj);
    },
    // 选择城市
    threeLevelArea(data) {
      this.paramsObj.region = data.join(',');
      this.$emit('changeValue', this.paramsObj);
    },
    changeValue() {
      this.$emit('changeValue', this.paramsObj);
    },
    handelArr(data) {
      if (!data) return [];
      if (typeof data === 'string') {
        return data.split(',');
      } else {
        return data;
      }
    },
    // 上传文件
    upProgress() {
      // this.createLoading = true;
    },
    complateSetData({ data, fileName }, key) {
      const fileList = {
        name: fileName,
        url: data.url,
        time: new Date().getTime()
      };
      if (typeof data === 'string') {
        fileList.url = data;
      } else {
        fileList.url = data.url;
      }
      if (this.paramsObj[key]) {
        this.paramsObj[key].push(fileList);
      } else {
        this.$set(this.paramsObj, key, [fileList]);
      }
      this.$emit('changeValue', this.paramsObj);
    },
    removeFileList({ file, index }, key) {
      this.paramsObj[key].splice(index, 1);
    },
    validateForm(validate = true) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs.formRef.validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject();
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    querySearch(queryString, cb) {
      if (!queryString || queryString.length > 30) {
        cb([]);
        return;
      }
      const params = {
        page: 1,
        perPage: 0,
        supplier: queryString,
        notShowNoAuthTip: true
      };
      supplierManageList(params).then(res => {
        if (res.data && res.data.items) {
          res.data.items.forEach(i => {
            i.value = i.supplier;
          });
          cb(res.data.items);
        } else {
          cb([]);
        }
      }).catch(() => {
        cb([]);
      });
    },
    handleSelect(item) {
      this.paramsObj.supplierId = item.supplierCode;
      this.paramsObj.channelId = null;
      this.$emit('setSupplierId', Number(item.id));
      this.$nextTick(() => {
        this.paramsObj.channelId = Number(item.id);
      });
    },
    channelNameChange() {
      this.paramsObj.channelId = null;
      this.$set(this.paramsObj, 'supplierId', '');
    },
    supplierTypeChange() {
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    // 获取所属部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      });
    },
    // 新建供应商
    toCreateSupplier() {
      if (!this.hasRouteAuth('medium:supplier:edit')) {
        this.$message.error('暂无供应商新建权限！');
        return;
      }
      const routeUrl = this.$router.resolve({
        name: 'supplierManage',
        query: {
          toCreate: 1
        }
      });
      window.open(routeUrl.href, '_blank');
    }
  }
};
</script>

<style lang="scss" scoped>
.width240 {
  width: 240px;
  &::v-deep {
    .el-select {
      width: 240px;
    }
    .el-input__inner {
      width: 240px;
    }
  }
}
.static-form-fields {
  &::v-deep {
    .el-form-item {
      margin-bottom: 2px !important;
    }
    .el-form-item__label {
      color: #999 !important;
    }
  }
}
.width172 {
  width: 172px;
  &::v-deep {
    .el-select {
      width: 172px;
    }
    .el-input__inner {
      width: 240px;
      padding-right: 68px
    }
  }
}
.dynamic-item-margin {
  margin-bottom: 24px;
  @media only screen and (min-width: 1300px) {
    margin-bottom: 16px;
  }
}
.expend-btn {
  display: inline-block;
  width: 66px;
  text-align: center;
  font-size: 14px;
  font-weight: bold;
  color: #406eff;
  cursor: pointer;
  position: relative;
  left: -3px;
  border-left: 1px solid #eee;
}
.expend-btn:hover {
  opacity: .8;
}
.mock-input {
  width: 240px;
  background-color: #F5F7FA;
  border:1px solid #E4E7ED;
  border-radius: 4px;
  height: 32px;
  line-height: 32px;
  color: #C0C4CC;
  cursor: not-allowed;
  padding: 0 8px;
  &.mock-input-mobile {
    width: auto;
  }
}
.height32 {
  &::v-deep {
    .el-cascader {
      line-height: 32px;
    }
  }
}
.supplier-tip {
  position: absolute;
  left: 0;
  top: 28px;
  color: #F56C6C;
  font-size: 12px;
}
.without-supplier-id {
  &::v-deep {
    .el-input__inner {
      border-color: #F56C6C !important;
    }
  }
}
.dividing {
  &::v-deep {
    .el-col {
      .el-form-item__content {
        border-right: 1px solid #EBEEFD !important;
      }
      &:nth-child(3n) {
        .el-form-item__content {
          border-right: none !important;
        }
      }
      &:last-child {
        .el-form-item__content {
          border-right: none;
        }
      }
      .el-form-item {
        margin-right: 10px;
      }
    }
  }
}
</style>
